<?php

namespace App\Service\Customer;

use App\Models\Customer\AddressModel;
use DB;
class AddressService
{
    /**
     * 增加收货地址
     */
    public static function addAddress(array $data)
    {
        if(!AddressModel::insert($data)){
            return false;
        }
        return true;
    }

    /**
     * 编辑收货地址
     */
    public static function changeAddress($id, array $data)
    {
        if(!AddressModel::where('id',$id)->update($data)){
            return false;
        }
        return true;
    }

    /**
     * 获取收货地址
     */
    public static function getAddress($uid)
    {
        $result = DB::table('lsj_ship_address')->where('uid',$uid)
            ->get()
            ->toArray();
        return $result;
    }

	/**
	 *  获取一个收货地址
	 */
	public static function getOneAddress($address_id,$uid)
	{
		$address = DB::table('lsj_ship_address')
			->where([
				'id' => $address_id,
				'uid' => $uid
			])
			->first();
		return $address;
	}

    /**
     * 默认收货地址
     */
    public static function defaultAddress($uid)
    {
        $result = DB::table('lsj_ship_address')->where([
            'uid' => $uid,
            'is_default' => 1
        ])->first();
        return $result;
    }

    /**
     * 删除收货地址
     */
    public static function deleteAddress($id)
    {
        if(!AddressModel::where('id',$id)->delete()){
            return false;
        }
        return true;
    }

    /**
     * 查询省市区
     */
    public static function getProvincesCityArea($type,$id)
    {
        $result = [];
        switch ($type){
            case 1: //省
                $result = DB::table('lsj_provinces')->get();
                break;
            case 2: //市
                $result = DB::table('lsj_cities')->where('provinceid',$id)->get();
                break;
            case 3: //区
                $result = DB::table('lsj_areas')->where('cityid',$id)->get();
                break;
        }

        return $result;
    }

    /**
     * 更改设置默认收货地址
     */
    public static function changeAddressDefault($id,$uid)
    {
        try{
            DB::beginTransaction();
            DB::table('lsj_ship_address')->where(['uid'=>$uid,'is_default'=>1])->update(['is_default'=>0]);
            DB::table('lsj_ship_address')->where('id',$id)->update(['is_default'=>1]);
            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            return true;
        }


    }
}